var express = require('express');
var process = require('child_process');
var config = require('../config/deploy-config.json');
var router = express.Router();

router.post('/', function(req, res, next) {
    var appName = req.query["app"];
    if(!appName){
        throw new Error('appName is null.');
    }
    console.log(JSON.stringify(config));
    var deployConfig = config["deployInfo"];
    var appConfig = config["apps"].appName;
    if (!deployConfig){
        throw new Error('deploy config err!');
    }
    if (!appConfig){
        throw new Error('app config err!.');
    }
    var basePath = deployConfig["basePath"];
    var appGitUrl = appConfig["gitUrl"];
    var outstr = '';
    process.exec("sh "+basePath+"/deploy.sh " + appName + " " + appGitUrl +" > out.log",function (error, stdout, stderr) {
        outstr = stdout;
        if (error !== null) {
            console.log('exec error: ' + error);
        }
    });
    res.send('respond with a resource'+outstr);
});
router.post('/test', function(req, res, next) {
    console.log(req);
    console.log(req.body);
    res.send('respond with a resource'+JSON.stringify(req.query)+","+JSON.stringify(req.body));
});

module.exports = router;
